<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

error_reporting( E_PARSE | E_ERROR | E_WARNING);
use think\Request;
// 应用公共文件
function pr($var) {
    $template = PHP_SAPI !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
    printf($template, print_r($var, true));
}
//字段排序
function descArray($x,$y){
    if($x['parameter']['addplate'] == $y['parameter']['addplate'])
        return 0;
    elseif($x['parameter']['addplate'] > $y['parameter']['addplate'])
        return -1;
    else
        return 1;
}
function absArray($x,$y){
    if($x['parameter']['buymoeny'] == $y['parameter']['buymoeny'])
        return 0;
    elseif($x['parameter']['buymoeny'] < $y['parameter']['buymoeny'])
        return -1;
    else
        return 1;
}
/**
 * @name php获取中文字符拼音首字母
 * @param $str
 * @return null|string
 * @author 潘军伟<panjunwei@ruiec.cn>
 * @time 2015-09-14 17:58:14
 */
function getFirstCharter($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) return 'A';
    if ($asc >= -20283 && $asc <= -19776) return 'B';
    if ($asc >= -19775 && $asc <= -19219) return 'C';
    if ($asc >= -19218 && $asc <= -18711) return 'D';
    if ($asc >= -18710 && $asc <= -18527) return 'E';
    if ($asc >= -18526 && $asc <= -18240) return 'F';
    if ($asc >= -18239 && $asc <= -17923) return 'G';
    if ($asc >= -17922 && $asc <= -17418) return 'H';
    if ($asc >= -17417 && $asc <= -16475) return 'J';
    if ($asc >= -16474 && $asc <= -16213) return 'K';
    if ($asc >= -16212 && $asc <= -15641) return 'L';
    if ($asc >= -15640 && $asc <= -15166) return 'M';
    if ($asc >= -15165 && $asc <= -14923) return 'N';
    if ($asc >= -14922 && $asc <= -14915) return 'O';
    if ($asc >= -14914 && $asc <= -14631) return 'P';
    if ($asc >= -14630 && $asc <= -14150) return 'Q';
    if ($asc >= -14149 && $asc <= -14091) return 'R';
    if ($asc >= -14090 && $asc <= -13319) return 'S';
    if ($asc >= -13318 && $asc <= -12839) return 'T';
    if ($asc >= -12838 && $asc <= -12557) return 'W';
    if ($asc >= -12556 && $asc <= -11848) return 'X';
    if ($asc >= -11847 && $asc <= -11056) return 'Y';
    if ($asc >= -11055 && $asc <= -10247) return 'Z';
    return null;
}

function uploadFile($file,$maxSize=1000000,$validExt=array(),$notValidExt=array('exe','php','asp','bat','asa','vbs')){

    if(!key_exists('name',$file) || !key_exists('type',$file) || !key_exists('tmp_name',$file) || !key_exists('error',$file) || !key_exists('size',$file)){
        $GLOBALS['upload_file_error']  = '第一个参数中缺少5要素';
        return false ;
    }

    //验证是否上传成功
    switch($file['error']){
        case '0':
            break ;
        case '1':
            $GLOBALS['upload_file_error'] = '文件大小超过了php.ini定义的upload_max_filesize的值';
            break;
        case '2':
            $GLOBALS['upload_file_error'] = '上传文件大小超过了HTML表单中max_file_size选项指定的值';
            break ;
        case '3':
            $GLOBALS['upload_file_error'] = '文件只有部分被上传';
            break ;
        case '4':
            $GLOBALS['upload_file_error']= '没有文件被上传';
            break ;
        case '6':
            $GLOBALS['upload_file_error'] = '找不到临时文件夹';
            break;
        case '7':
            $GLOBALS['upload_file_error'] = '写文件失败';
            break;
        case '8':
            $GLOBALS['upload_file_error'] = '上传被其他扩展中断';
            break;
        default:
            $GLOBALS['upload_file_error'] = '未知错误';
            break;
    }



    if($GLOBALS['upload_file_error']) return false ;
    //是不是一个上传文件
    if(!is_uploaded_file($file['tmp_name'])){
        $GLOBALS['upload_file_error'] = '不是上传文件';
        return false ;
    }
    //验证最大上传大小
    if($file['size'] > $maxSize) {
        $GLOBALS['upload_file_error'] = '文件最大允许上传'.return_size($maxSize);
        return false ;
    }

    //获取上传文件后缀
    $extArr  = explode('.',$file['name']);
    $ext     = strtolower(array_pop($extArr)) ;//文件后缀
    //验证允许上传的文件后缀
    if($validExt && !in_array($ext,$validExt)){
        $GLOBALS['upload_file_error'] = '文件格式上传错误，只允许上传后缀为'.implode('、',$validExt).'的文件';
        return false ;
    }

    //验证不允许上传的文件后缀
    if($notValidExt && in_array($ext,$notValidExt)){
        $GLOBALS['upload_file_error'] ='文件格式上传错误，不允许上传后缀为'.$ext.'的文件';
        return false ;
    }
    $name = explode('.',$file['name']);
    $dirpath    =   'Public' .'/uploads/';
    if(!file_exists($dirpath))  mkdir($dirpath);
    $dirpath .= @date('Ymd');
    if(!file_exists($dirpath))  mkdir($dirpath);
    $filename = $name[0].'-'.@date('Ymd').uniqid(mt_rand()).'.'.$ext ;

    move_uploaded_file($file['tmp_name'] , dirname(APP_PATH) . DS . $dirpath. DS .$filename) ;
    return $dirpath. '/' .$filename ;
}
//php 转对象
function arrayToObject($e){
    if( gettype($e)!='array' ) return;
    foreach($e as $k=>$v){
        if( gettype($v)=='array' || getType($v)=='object' )
            $e[$k]=(object)arrayToObject($v);
    }
    return (object)$e;
}
//php 转数组
function objectToArray($e){
    $e=(array)$e;
    foreach($e as $k=>$v){
        if( gettype($v)=='resource' ) return;
        if( gettype($v)=='object' || gettype($v)=='array' )
            $e[$k]=(array)objectToArray($v);
    }
    return $e;
}

/**
 * 将一个数组转换为 XML 结构的字符串
 * @param array $arr 要转换的数组
 * @param int $level 节点层级, 1 为 Root.
 * @return string XML 结构的字符串
 */
function array2xml($arr, $level = 1) {
    $s = $level == 1 ? "<xml>" : '';
    foreach($arr as $tagname => $value) {
        if (is_numeric($tagname)) {
            $tagname = $value['TagName'];
            unset($value['TagName']);
        }
        if(!is_array($value)) {
            $s .= "<{$tagname}>".(!is_numeric($value) ? '<![CDATA[' : '').$value.(!is_numeric($value) ? ']]>' : '')."</{$tagname}>";
        } else {
            $s .= "<{$tagname}>" . array2xml($value, $level + 1)."</{$tagname}>";
        }
    }
    $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
    return $level == 1 ? $s."</xml>" : $s;
}

function istrlen($string, $charset='UTF8') {

    if(strtolower($charset) == 'gbk') {
        $charset = 'gbk';
    } else {
        $charset = 'utf8';
    }
    if(function_exists('mb_strlen')) {
        return mb_strlen($string, $charset);
    } else {
        $n = $noc = 0;
        $strlen = strlen($string);

        if($charset == 'utf8') {

            while($n < $strlen) {
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $n += 2; $noc++;
                } elseif(224 <= $t && $t <= 239) {
                    $n += 3; $noc++;
                } elseif(240 <= $t && $t <= 247) {
                    $n += 4; $noc++;
                } elseif(248 <= $t && $t <= 251) {
                    $n += 5; $noc++;
                } elseif($t == 252 || $t == 253) {
                    $n += 6; $noc++;
                } else {
                    $n++;
                }
            }

        } else {

            while($n < $strlen) {
                $t = ord($string[$n]);
                if($t>127) {
                    $n += 2; $noc++;
                } else {
                    $n++; $noc++;
                }
            }

        }

        return $noc;
    }
}

function url_encode($str) {
    if(is_array($str)) {
        foreach($str as $key=>$value) {
            $str[urlencode($key)] = url_encode($value);
        }
    } else {
        $str = urlencode($str);
    }

    return $str;
}
/**
 * 转义字符串的HTML
 * @param string or array $var
 * @return string or array
 *			 返回转义后的字符串或是数组
 */
function ihtmlspecialchars($var) {
    if (is_array($var)) {
        foreach ($var as $key => $value) {
            $var[htmlspecialchars($key)] = ihtmlspecialchars($value);
        }
    } else {
        $var = str_replace('&amp;', '&', htmlspecialchars($var, ENT_QUOTES));
    }
    return $var;
}
/**
 * 是否包含子串
 */

function strexists($string, $find) {
    return !(strpos($string, $find) === FALSE);
}

function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) {
    $urlset = parse_url($url);
    if(empty($urlset['path'])) {
        $urlset['path'] = '/';
    }
    if(!empty($urlset['query'])) {
        $urlset['query'] = "?{$urlset['query']}";
    }
    if(empty($urlset['port'])) {
        $urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
    }
    if (strexists($url, 'https://') && !extension_loaded('openssl')) {
        if (!extension_loaded("openssl")) {
            //die('请开启您PHP环境的openssl');
        }
    }
    if(function_exists('curl_init') && function_exists('curl_exec')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $urlset['scheme']. '://' .$urlset['host'].($urlset['port'] == '80' ? '' : ':'.$urlset['port']).$urlset['path'].$urlset['query']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        if($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            if (is_array($post)) {
                $post = http_build_query($post);
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        if (defined('CURL_SSLVERSION_TLSv1')) {
            curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
        if (!empty($extra) && is_array($extra)) {
            $headers = array();
            foreach ($extra as $opt => $value) {
                if (strexists($opt, 'CURLOPT_')) {
                    curl_setopt($ch, constant($opt), $value);
                } elseif (is_numeric($opt)) {
                    curl_setopt($ch, $opt, $value);
                } else {
                    $headers[] = "{$opt}: {$value}";
                }
            }
            if(!empty($headers)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            }
        }
        $data = curl_exec($ch);
        $status = curl_getinfo($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($errno || empty($data)) {
            //return error(1, $error);
        } else {
            return ihttp_response_parse($data);
        }
    }
    $method = empty($post) ? 'GET' : 'POST';
    $fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
    $fdata .= "Host: {$urlset['host']}\r\n";
    if(function_exists('gzdecode')) {
        $fdata .= "Accept-Encoding: gzip, deflate\r\n";
    }
    $fdata .= "Connection: close\r\n";
    if (!empty($extra) && is_array($extra)) {
        foreach ($extra as $opt => $value) {
            if (!strexists($opt, 'CURLOPT_')) {
                $fdata .= "{$opt}: {$value}\r\n";
            }
        }
    }
    $body = '';
    if ($post) {
        if (is_array($post)) {
            $body = http_build_query($post);
        } else {
            $body = urlencode($post);
        }
        $fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
    } else {
        $fdata .= "\r\n";
    }
    if($urlset['scheme'] == 'https') {
        $fp = fsockopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
    } else {
        $fp = fsockopen($urlset['host'], $urlset['port'], $errno, $error);
    }
    stream_set_blocking($fp, true);
    stream_set_timeout($fp, $timeout);
    if (!$fp) {
        //return error(1, $error);
    } else {
        fwrite($fp, $fdata);
        $content = '';
        while (!feof($fp))
            $content .= fgets($fp, 512);
        fclose($fp);
        return ihttp_response_parse($content, true);
    }
}

function ihttp_response_parse($data, $chunked = false) {
    $rlt = array();
    $pos = strpos($data, "\r\n\r\n");
    $split1[0] = substr($data, 0, $pos);
    $split1[1] = substr($data, $pos + 4, strlen($data));

    $split2 = explode("\r\n", $split1[0], 2);
    preg_match('/^(\S+) (\S+) (\S+)$/', $split2[0], $matches);
    $rlt['code'] = $matches[2];
    $rlt['status'] = $matches[3];
    $rlt['responseline'] = $split2[0];
    $header = explode("\r\n", $split2[1]);
    $isgzip = false;
    $ischunk = false;
    foreach ($header as $v) {
        $row = explode(':', $v);
        $key = trim($row[0]);
        $value = trim($row[1]);
        if (is_array($rlt['headers'][$key])) {
            $rlt['headers'][$key][] = $value;
        } elseif (!empty($rlt['headers'][$key])) {
            $temp = $rlt['headers'][$key];
            unset($rlt['headers'][$key]);
            $rlt['headers'][$key][] = $temp;
            $rlt['headers'][$key][] = $value;
        } else {
            $rlt['headers'][$key] = $value;
        }
        if(!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
            $isgzip = true;
        }
        if(!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
            $ischunk = true;
        }
    }
    if($chunked && $ischunk) {
        $rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
    } else {
        $rlt['content'] = $split1[1];
    }
    if($isgzip && function_exists('gzdecode')) {
        $rlt['content'] = gzdecode($rlt['content']);
    }

    //$rlt['meta'] = $data;
    if($rlt['code'] == '100') {
        return ihttp_response_parse($rlt['content']);
    }
    return $rlt;
}

function ihttp_response_parse_unchunk($str = null) {
    if(!is_string($str) or strlen($str) < 1) {
        return false;
    }
    $eol = "\r\n";
    $add = strlen($eol);
    $tmp = $str;
    $str = '';
    do {
        $tmp = ltrim($tmp);
        $pos = strpos($tmp, $eol);
        if($pos === false) {
            return false;
        }
        $len = hexdec(substr($tmp, 0, $pos));
        if(!is_numeric($len) or $len < 0) {
            return false;
        }
        $str .= substr($tmp, ($pos + $add), $len);
        $tmp  = substr($tmp, ($len + $pos + $add));
        $check = trim($tmp);
    } while(!empty($check));
    unset($tmp);
    return $str;
}


function ihttp_get($url) {
    return ihttp_request($url);
}

function ihttp_post($url, $data) {
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');
    return ihttp_request($url, $data, $headers);
}

function gets($url=NULL){
    if($url){
        $rslt  = ihttp_get($url);
        if(strtolower(trim($rslt['status'])) == 'ok'){
            //pr($rslt) ;exit;
            if(is_json($rslt['content'])){ //返回格式是json 直接返回数组
                $return =  json_decode($rslt['content'],true);
                if($return['errcode']) //有错误
                    exit('Error:<br>Api:'.$url.'  <br>errcode:'.$return['errcode'].'<br>errmsg:'.$return['errmsg']);
                return $return ;
            }else{  //先暂时直接返回，以后其它格式再增加
                return $rslt['content'] ;
            }
        }
        exit('远程请求失败：'.$url);
    }
    exit('未发现远程请求地址');
}
/**
远程post请求
 */
function posts($url=NULL, $data=NULL){
    if($url && $data){
        $rslt  = ihttp_post($url,$data);
        if(strtolower(trim($rslt['status'])) == 'ok'){
            //pr($rslt) ;
            if(is_json($rslt['content'])){ //返回格式是json 直接返回数组
                $return =  json_decode($rslt['content'],true);
                if($return['errcode']) //有错误
                    exit('Error:<br>Api:'.$url.'  <br>errcode:'.$return['errcode'].'<br>errmsg:'.$return['errmsg']);
                return $return ;
            }else{  //先暂时直接返回，以后其它格式再增加
                return $rslt['content'] ;
            }
        }
        exit('远程请求失败：'.$url);
    }
    exit('post远程请求，参数错误');
}


function is_json($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

/**
 * excel表格导出
 * @param string $fileName 文件名称
 * @param array $headArr 表头名称
 * @param array $data 要导出的数据
 * @author static7  */
function excelExport($fileName = '', $headArr = [], $data = []) {
    $fileName .= "_" . date("Y_m_d",Request::instance()->time()) . ".xls";
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties();
    $key = ord("A"); // 设置表头
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) { // 行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) { // 列写入
            $objActSheet->setCellValue(chr($span) . $column, $value);
            $span++;
        }
        $column++;
    }
    ob_clean();
    $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
    $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
    header('Content-Type:application/vnd.ms-excel;charset=utf-8');
    header("Content-Disposition: attachment;filename='$fileName'");
    header('Cache-Control: max-age=0');

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); // 文件通过浏览器下载
    exit();
}

//证件识别
  function makePostData($filePath, $picType)
{
   if (!function_exists('curl_file_create')) {
       function curl_file_create($fileName, $mimeType = '', $postName = '')
       {
           return "@$fileName;filename=".($postName ?: basename($fileName)).($mimeType ? ";type=$mimeType" : '');
       }
   }
   $cFile = curl_file_create($filePath, $picType, md5(date('Y-m-d H:i:s')).'.jpg');
   return [
       'key' => '8e0a2380be553c4738a997450ed09fc4',
       'cardType' => '2',//2表示身份证正面,一定要看清楚你的图片到底是什么类型的图片
       'pic' => $cFile,
   ];
}

 function upload($postData)
{
   $httpInfo = [];
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, 'http://v.juhe.cn/certificates/query.php');
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果成功,只将结果返回,不自动输出任何内容,如果失败返回false
   //设置为post请求类型
   curl_setopt($ch, CURLOPT_POST, 1);
   //设置具体的post数据
   curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
   $response = curl_exec($ch);
   if ($response === false) {
       //如果提示你上传图片太小等,可以打印出$cFile这个变量看看具体图片信息
       //一般因为路径引起的错误都会提示:couldn't open file "cc.jpg"
       echo 'cURL Error: '.curl_error($ch);
       return false;
   }
   $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
   if ($httpCode != 200) {
       echo '服务器状态码:'.$httpCode;
   }
   $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
   curl_close($ch);
   return $response;
}


   

